import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import type { ResponseData } from "./type";
import { baseConfig } from "./config";
import { defaultRequestInterceptor, defaultResponseInterceptor, dealHttpCodeError } from "./interceptors";

/** 自定义请求类 */
export class Request {
  /** axios 实例 */
  private instance: AxiosInstance;
  /** 基础配置 */
  protected baseConfig: AxiosRequestConfig = baseConfig;

  constructor(config?: AxiosRequestConfig) {
    this.instance = axios.create({ ...this.baseConfig, ...config });

    this.useRequestInterceptors();
    this.useResponseInterceptors();
  }

  /** 请求拦截器 */
  private useRequestInterceptors() {
    this.instance.interceptors.request.use(defaultRequestInterceptor);
  }

  /** 响应拦截器 */
  private useResponseInterceptors() {
    this.instance.interceptors.response.use(defaultResponseInterceptor, dealHttpCodeError);
  }

  /** 基本原始请求 */
  public request<T>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.instance.request(config);
  }

  /** get 请求 */ //<AxiosResponse<ResponseData<T>>>
  public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.get(url, config);
  }

  /** post 请求 */ //<AxiosResponse<ResponseData<T>>>
  public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.post(url, data, config);
  }

  /** put 请求 */ // <AxiosResponse<ResponseData<T>>>
  public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.put(url, data, config);
  }

  /** delete 请求*/ //<AxiosResponse<ResponseData<T>>>
  public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.delete(url, config);
  }
}
